<template>
<div class="flow-step__wrap" ref="flowSteps">
  <div class="flow-step">
    <div class="step-card">
      <el-input
        size="mini"
        :placeholder="$t('configLazyLoad.businessConfig.enterStepNameQuery')"
        class="card-input"
        v-model="name"
      >
        <i
          class="el-input__icon el-icon-search"
          slot="suffix"
          @click.stop="search">
        </i>
      </el-input>
      <div class="step-card__step" :style="{height: stepHeight}">
        <div v-for="(item, index) in flowSteps"
             class="card-item"
             :key="index"
             @click.stop="currentStep(index, item._id)"
             :class="{'card-item__active': item._id === currentObj._id}"
             v-if="item.name.indexOf(name) !== -1">
          <i :class="stepTypeFn(item)"
             class="fl iconfont"></i>
          {{item.name}}
          <el-popover
            placement="right"
            trigger="hover"
            :content="$t('configLazyLoad.businessConfig.StepNotRelated')"
            popper-class=""
          >
            <i class="el-icon-warning fr" slot="reference" v-show="relatedStep.indexOf(item._id) === -1"></i>
          </el-popover>
        </div>
      </div>
      <div class="card-add" @click.stop="addStep">
        <i class="el-icon-plus"></i>{{$t('configLazyLoad.businessConfig.newSteps')}}
      </div>
    </div>
    <div class="step-tabs">
      <div class="fr step-btns">
        <el-popover
          placement="top"
          trigger="hover"
          :content="$t('monitor.tooltipAgentRate')"
          popper-class="common-tootip"
        >
          {{$t('configLazyLoad.businessConfig.stepTip')}}:<br>
          {{$t('configLazyLoad.businessConfig.stepTip1')}} <br>
          {{$t('configLazyLoad.businessConfig.stepTip2')}} <br>
          {{$t('configLazyLoad.businessConfig.stepTip3')}} <br>
          <el-button type="text"
                     slot="reference"
                     class="primary_btn text_btn"
                     icon="iconfont icon-jingshi fl"
                     size="mini">&nbsp;{{$t('configLazyLoad.businessConfig.stepTip')}}
          </el-button>
        </el-popover>
        &nbsp;&nbsp;
        <el-button type="text"
                   class="primary_btn text_btn"
                   @click.stop="toTop"
                   icon="iconfont icon-yulan fl"
                   size="mini">&nbsp;{{$t('configLazyLoad.businessConfig.processPreview')}}
        </el-button>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick" type="card">
        <el-tab-pane :label="$t('webchat.basicInfo')" name="stepInfo" class="tab-item">
          <!--步骤信息-->
          <step-info ref="stepInfo"
                     :currentStepInfo="currentObj"
                     class="step-info"
          ></step-info>
        </el-tab-pane>
        <el-tab-pane :label="$t('configLazyLoad.businessConfig.stepInterface')"
                     name="stepLayout"
                     class="tab-item">
          <div style="padding: 20px;">
            <div class="prompt">
              {{$t('configLazyLoad.businessConfig.tip')}}<br>
              <template v-if="currentObj.isBegin">
                {{$t('configLazyLoad.businessConfig.tip1')}}<br>
                {{$t('configLazyLoad.businessConfig.tip2')}}<br>
                {{$t('configLazyLoad.businessConfig.tip3')}}
              </template>
              <template v-else>
                {{$t('configLazyLoad.businessConfig.tip1')}}<br>
                {{$t('configLazyLoad.businessConfig.tip4')}}<br>
                {{$t('configLazyLoad.businessConfig.tip3')}}
              </template>
            </div>
            <div style="text-align: right">
              <el-button type="text"
                         class="primary_btn text_btn"
                         @click.stop="addFields"
                         icon="el-icon-plus"
                         size="mini">{{$t('configLazyLoad.businessConfig.addFields')}}</el-button>
              <el-button type="text"
                         class="primary_btn text_btn"
                         @click.stop="editStepLayout"
                         icon="el-icon-edit-outline"
                         size="mini">{{$t('public.edit')}}</el-button>
            </div>
            <!--步骤界面展示-->
            <fields-layout class="step-layout"
                           ref="fieldsLayout"
                           :currentStepInfo="currentObj"
                           :flowInfo="flowInfo"></fields-layout>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('configLazyLoad.businessConfig.stepAction')"
                                   name="flowAction"
                                   v-if="currentObj.type === 'user'"
      >
        <!--步骤动作-->
        <flow-action :currentStepInfo="currentObj"
                     :flowSteps="flowSteps"
                     ref="flowAction"
                     style="border-top: none;"
        >
        </flow-action>
      </el-tab-pane>
        <el-tab-pane :label="$t('configLazyLoad.businessConfig.trigger')"
                     v-if="!currentObj.isBegin"
                     name="flowTrigger">
          <div class="prompt prompt-trigger">
            {{$t('configLazyLoad.businessConfig.tip')}}<br>
            {{$t('configLazyLoad.businessConfig.tip5')}}
          </div>
          <flow-trigger ref="flowTrigger"
                        @openDialog="openTriggerForm"
                        :currentStepInfo="currentObj"></flow-trigger>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <affix :label="$t('configLazyLoad.businessConfig.processPreview')" ref="busChart">
    <!--工单流程图-->
    <bus-chart :flowSteps="flowSteps" :relatedStep="relatedStep" ref="chartSvg">     
    </bus-chart>
  </affix>
  <!--右侧滑出弹框-->
  <right-layout :visible="dialogObj.visible"
                :title="dialogObj.title"
                @close="close"
                @save="save"
                :width="dialogObj.width">
    <!--步骤界面设置-->
    <bus-drag :fieldsArr="stepFields"
              v-show="dialogObj.type === 'busDrag'"
              ref="busDrag"
    ></bus-drag>
    <!--添加字段-->
    <field-info ref="addField"
                :custFieldsList="custFieldsList"
                v-show="dialogObj.type === 'addField'"
    >
    </field-info>
    <trigger-form ref="triggerForm"
                  v-if="dialogObj.type === 'triggerForm'"
                  :currentStep="currentObj"
                  :defaultAgent="defaultAgent"></trigger-form>
  </right-layout>
</div>
</template>

<script>
  import stepInfo from './stepInfo'
  import rightLayout from '../base/rightLayout'
  import affix from '../../../../ui-modules/affix/Affix'
  import busChart from '../base/busChart'
  import fieldsLayout from './fieldsLayout'
  import busDrag from '../base/busDrag'
  import flowAction from './flowAction'
  import fieldInfo from './fieldInfo'
  import triggerForm from './triggerForm'
  import flowTrigger from './flowTrigger'
  import {getRoleAgents,getQueueAgents} from '../../../../../utils/workflowUtils'
  export default {
    name: 'flow-step',
    props: {
    },
    data () {
      return {
        name: '',
        activeName: '',
        dialogObj: {
          visible: false,
          title: '',
          type: 'busDrag',
          state: '',
          width: '840px'
        },
        defaultAgent: [],
        custFieldsList: [],
        stepHeight: `calc(100vh - ${this.busType === 'newFlow' ? '350px' : '365px'})`
      }
    },
    inject: ['busType'],
    components: {
      stepInfo,
      rightLayout,
      affix,
      busChart,
      fieldsLayout,
      busDrag,
      fieldInfo,
      flowAction,
      flowTrigger,
      triggerForm
    },
    computed: {
      flowSteps () {
        return this.$store.state.config.businessConfig[this.busType].flowSteps || []
      },
      flowInfo () {
        return this.$store.state.config.businessConfig[this.busType].flowInfo || {}
      },
      // 当前步骤
      currentObj () {
        let business = this.$store.state.config.businessConfig[this.busType] || {}
        return business.flowSteps[business.currentStepIndex] || {}
      },
      // 步骤界面设置要展示的字段
      stepFields () {
        // 步骤界面为空时，如果有lastStepFields，则展示改字段
        let stepFields = this.currentObj.stepFields || []
        let lastStepFields = this.currentObj.lastStepFields || []
        return stepFields.length !== 0 ? stepFields : lastStepFields
      },
      // 关联步骤数组
      relatedStep () {
        return this.relate(this.flowSteps)
      }
    },
    methods: {
      close () {
        this.dialogObj.visible = false
      },
      save () {
        if (this.dialogObj.type === 'busDrag') {
          this.stepLayoutSave()
        } else if (this.dialogObj.type === 'addField') {
          this.addFieldsSave()
        } else if (this.dialogObj.type === 'triggerForm') {
          let data = this.$refs.triggerForm.submit()
          this.$refs.flowTrigger.save(this.dialogObj.state, data, () => {
            this.dialogObj.visible = false
          })
        }
      },
      editStepLayout () {
        this.dialogObj.visible = true
        this.dialogObj.title = this.$t('configLazyLoad.businessConfig.editStepPage')
        this.dialogObj.type = 'busDrag'
        this.dialogObj.width = '840px'
        this.$refs.busDrag.initData()
      },
      openTriggerForm (state, data) {
        this.dialogObj.visible = true
        this.dialogObj.title = this.$t('configLazyLoad.businessConfig.editStepPage')
        this.dialogObj.type = 'triggerForm'
        this.dialogObj.state = state
        this.dialogObj.width = '900px'
        this.$nextTick(() => {
          this.$refs.triggerForm.initForm(data)
        })
      },
      /*
      * 添加字段
      * */
      addFields () {
        this.dialogObj.visible = true
        this.dialogObj.title = this.$t('configLazyLoad.businessConfig.addFields')
        this.dialogObj.width = ''
        this.dialogObj.type = 'addField'
        this.$refs.addField.initData('add')
      },
      // 添加字段保存
      addFieldsSave () {
        let data = this.$refs.addField.create()
        if (!data.success) {
          return
        }
        let form = data.data
        form.flow_id = this.flowInfo._id
        this.$store.dispatch('addBusinessFlowFields', form).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('config.customer.addSucc'))
            this.$store.commit('flowConfig/UPDATE_FLOW_FIELD', {type: 'add', data: res.newData})
            this.dialogObj.visible = false
          }
        })
      },
      toTop () {
        // 滚到工单流程图
        let achor = this.$refs.busChart.$el
        this.$emit('toTop', achor.offsetTop)
      },
      // 保存步骤界面
      stepLayoutSave () {
        let stepFields = this.$refs.busDrag.submit()
        this.$store.dispatch('updateBusinessStepFields', {flow_id: this.currentObj.flow_id, _id: this.currentObj._id, stepFields}).then((res) => {
          if (res.success) {
            this.$store.commit('flowConfig/UPDATE_FLOW_STEP', {type: 'update', data: {stepFields: res.steps}})
            this.dialogObj.visible = false
            this.$nextTick(() => {
              this.$refs.fieldsLayout.initData()
            })
          }
        })
      },
      // 计算关联步骤
      relate (steps) {
        let arr = []
        steps.some((item) => {
          if (item.isBegin) {
            // 从开始步骤开始遍历
            if (item.actions.length) {
              arr.push(item._id)
              this.relateItem(item, arr, steps)
            }
          }
        })
        return arr
      },
      // 关联步骤递归
      relateItem (item, arr, steps) {
        item.actions.forEach((item) => {
          if (arr.indexOf(item.jumpTo) === -1) {
            arr.push(item.jumpTo)
            steps.forEach((one) => {
              if (one._id === item.jumpTo) {
                this.relateItem(one, arr, steps)
              }
            })
          }
        })
      },
      // 切换当前步骤
      currentStep (index, _id) {
        this.activeName = 'stepInfo'
        this.$store.commit('flowConfig/CHANGE_CURRENT_INDEX', {currentStepIndex: index})
        this.$store.dispatch('queryBusinessFlowStep', {_id}).then((res) => {
          if (res.success) {
            res.data.lastStepFields = res.lastStepFields
            this.$store.commit('flowConfig/UPDATE_FLOW_STEP', {type: 'update', data: res.data})
            this.$nextTick(() => {
              this.handleClick({name: 'stepInfo'})
            })
          }
        })
      },
      // 初始化,默认点击第一步
      initData () {
        let firstSteps = this.flowSteps[0] || {}
        this.dialogObj.visible = false
        firstSteps._id && this.currentStep(0, firstSteps._id)
        this.$nextTick(() => {
          if (this.$refs.chartSvg.actionNum > 40) {
            this.$refs.chartSvg.textToSvg('graph LR; \n ')
          } else {
            this.$refs.chartSvg.textToSvg()
          }
        })
      },
      stepTypeFn (item) {
        if (item.isBegin) {
          return ['icon-bus_begin']
        } else {
          return ['icon-bus_' + (item.systemFn ? item.systemFn : 'step')]
        }
      },
      /*
      *添加工单步骤
      * */
      addStep () {
        let data = {
          _id: this.flowInfo._id, name: this.$t('configLazyLoad.businessConfig.unnamedStep'), ctime: '', ctype: 'min', notifyUser: ''
        }
        this.$store.dispatch('addBusinessFlowStep', data).then((res) => {
          if (res.success) {
            this.$message.success( this.$t('configLazyLoad.businessConfig.addProcessingStepSuccess'))
            this.$store.commit('flowConfig/UPDATE_FLOW_STEP', {type: 'add', data: res.data})
            // 激活当前步骤
            this.$nextTick(() => {
              let index = this.flowSteps.length - 1
              this.currentStep(index, res.data._id)
            })
          }
        })
      },
      // 生成默认处理人
      async filterAgent () {
        let actions = this.currentObj.actions || []
        let roles = []
        let queues = []
        for (let i = 0; i < actions.length; i++) {
          let actionsItem = actions[i]
          // 判断角色还是技能组
          if(actionsItem.actionAllow === 1){
            if(actionsItem.actionQueue.length>0){ // 技能组
              actionsItem.actionQueue.forEach(item=>{
                queues.push(item)
              })
            }
          } else {
            //兼容老数据，之前是字符串
            if(!Array.isArray(actionsItem.actionRole)){
              actionsItem.actionRole = [actionsItem.actionRole]
            }
            // 角色
            if(actionsItem.actionRole.length>0){
              actionsItem.actionRole.forEach(item=>{
                roles.push(item)
              })
            } 
          }
        }
        // 多个步骤动作，会存在角色和技能组同时存在的情况
        let queueAgentList = []
        let roleAgentList = []
        if(roles.length>0){
          roleAgentList = getRoleAgents(roles, false, 'busConfig') || []
        } 
        if (queues.length>0) {
          // 获取工单技能组
          queueAgentList = await getQueueAgents(queues, false)
        }
        let agents = [...new Set(roleAgentList.concat(queueAgentList))]
        let data = agents.map((item) => {
          let label = item.displayName
          // ‘工单创建人’没有exten
          if (item.exten) {
            label += `[${item.exten}]`
          }
          return {label, value: item._id, status:item.status}
        })
        this.defaultAgent = data
      },
      handleClick ({name}) {
        this.activeName = name
        if (name === 'stepInfo') {
          this.$refs.stepInfo.initData()
        } else if (name === 'stepLayout') {
          this.$nextTick(() => {
            this.$refs.fieldsLayout.initData()
            this.$store.dispatch('getCustomerTemplate', {account: this.$store.state.session.user.account}).then((res) => {
              if (res.success) {
                let custTmpl = res.data[0]
                this.custFieldsList = [{label: this.$t('configLazyLoad.businessConfig.notAssociated'), value: 'no'}]
                console.log(res)
                if (custTmpl) {
                  let stableFields = custTmpl.stable_fields || []
                  stableFields.forEach((item) => {
                    // 省市县算一个字段
                    if (item.name !== 'province' && item.name !== 'city' && item.name !== 'district') {
                      this.custFieldsList.push({label: item.value, value: 'stable_' + item.name, type: 'single'})
                    } else if (item.name === 'province') {
                      this.custFieldsList.push({label: '省市县', value: 'stable_' + item.name, type: 'dropdown'})
                    }
                  })
                  let customFields = custTmpl.custom_fields || []
                  customFields.forEach((item) => {
                    if (item.status === 'stop') {
                      return
                    }
                    // 字典id，导出工单时使用
                    let dicId = item.dic && item.dic.isDic && item.dic.dicId || ''
                    this.custFieldsList.push({label: item.name, value: 'custom_' + item._id, type: item.type, dicId})
                  })
                }
              }
            })
          })
        } else if (name === 'flowAction') {
          this.$nextTick(() => {
            this.$refs.flowAction.initData()
          })
        } else if (name === 'flowTrigger') {
          this.$nextTick(() => {
            this.filterAgent()
            this.$refs.flowTrigger.initData()
          })
        }
      }
    }
  }
</script>

<style scoped lang='stylus'>
  @import '../../../../../assets/common.styl'
  .flow-step__wrap
    position relative
    padding 20px
  .flow-step
    display flex
    flex-direction row
    position relative
    padding-bottom 20px
  .step-card
    width 200px
    flex-shrink 0
    .card-input
      margin-bottom 10px
    .step-card__step
      margin-bottom 10px
      overflow-y auto
    .card-item
      padding 0 10px
      line-height 38px
      box-sizing border-box
      border 1px solid $c-border2
      margin-bottom 4px
      .iconfont
        padding-right 2px
        color $cf-gray5
      .el-icon-warning
        color $cf-color0
        margin-top 13px
      &:hover
        background-color $c-main
        color $cf-white
        cursor pointer
        .iconfont
          color $cf-white
        .el-icon-warning
          color $cf-white
    .card-item.card-item__active
      background-color $c-main
      color $cf-white
      cursor pointer
      .el-icon-warning
        color $cf-white
      .iconfont
        color $cf-white
    .card-add
      padding 0 10px
      line-height 38px
      box-sizing border-box
      color $c-main
      font-size 14px
      text-align center
      border 1px dashed $c-border2
      margin-bottom 4px
      .el-icon-plus
        display inline-block
        margin-right 2px
      &:hover
        background-color $c-main
        color $cf-white
        cursor pointer
  .step-tabs
    flex-grow 1
    margin-left 20px
    .step-info
      width: 360px
    .tab-item
      border 1px solid #e4e7ed
      border-top none
    .step-layout
      background-color #f6f6f6
      padding 18px 20px
      min-height 100px
    .prompt
      color $c-prompt
    .prompt-trigger
      padding 20px
      border-right 1px solid $c-border2
      border-left 1px solid $c-border2
  .step-btns
    position relative
    z-index 1
  .text_btn
    padding 0
    min-width 0
  .el-icon-warning
    color $cf-color0
</style>
